package com.kuns.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密util，对application.yml中的明文密码进行加密
 *
 * 使用druid自带的加密工具
 *
 *  一般是拿私钥来加密生成一个加密串，然后解密的时候用公钥来解密得到原来的密码
 */
public class DruidEncryptUtil {

    // 公钥
    private static String publicKey;

    // 私钥
    private static String privateKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            System.out.println("privateKey= " + privateKey);
            publicKey = keyPair[1];
            System.out.println("publicKey= " + publicKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    // 加密方法 拿私钥来加密
    public static String encrypt(String plaintText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plaintText);
        System.out.println("encrypt= " + encrypt);
        return encrypt;
    }

    // 解密方法，拿公钥来解密
    public static String decrypt(String encrypt) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, encrypt);
        System.out.println("decrypt= " + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("Wing1Q2W#E");
        System.out.println("加密串：" + encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println("解密串：" + decrypt);
    }

}
